package top.chukongxiang.dubboboot.simple.gateway.oauth2.provider.cas;

import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import top.chukongxiang.dubboboot.simple.common.model.entity.user.User;
import top.chukongxiang.dubboboot.simple.common.service.UserService;
import top.chukongxiang.dubboboot.simple.gateway.oauth2.UserInfo;

import java.util.Map;

/**
 * @author 楚孔响
 * @version 1.0
 * @date 2021/12/31 16:45
 */
@Component
public class CasAuthenticationUserDetailsServiceImpl implements AuthenticationUserDetailsService<CasAssertionAuthenticationToken> {

    @DubboReference
    UserService userService;

    @Override
    public UserDetails loadUserDetails(CasAssertionAuthenticationToken token) throws UsernameNotFoundException {
        Map<String, Object> userAttributes = token.getAssertion().getPrincipal().getAttributes();
        String staffId = (String) userAttributes.get("eduPersonStaffID");
        if (staffId == null) {
            throw new UsernameNotFoundException("无法获取员工号");
        }

        User user = userService.getById(staffId);

        if (user == null) {
            throw new UsernameNotFoundException("当前用户无权限，请联系管理员");
        }

        return new UserInfo(user.getUsername(), user.getUsername());
    }
}
